package com.jijia.webbase.filter;

import com.jijia.webbase.config.security.LoginUser;
import com.jijia.webbase.config.security.SaveLoginUser;
import com.jijia.webbase.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// JwtAuthFilter.java
// 5. JWT认证过滤器
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
//        获取请求的url
        String url = request.getRequestURI();
        log.debug("JwtAuthenticationFilter过滤器中 url: {}", url);
        if (url.startsWith("/login") || url.startsWith("/register")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 从请求头获取token
        String token = request.getHeader("Authorization");
        log.debug("过滤器中 token: {}", token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                Claims claims = jwtUtil.parseToken(token);
                String username = claims.getSubject();

                log.debug("从token中获取的username: {}", username);
                    // 创建Authentication对象
                SaveLoginUser loginUser = jwtUtil.getUser("token_"+username); // 需要从数据库加载或缓存获取
                if (!loginUser.getToken().equals(token)){
                    throw new RuntimeException("token验证失败！");
                }


                log.debug("从redis中获取的loginUser: {}", loginUser);
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(loginUser, null, null);
                    SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (Exception e) {
                // token验证失败处理
                log.error("token验证失败: {}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 HTTP 状态码为 401 Unauthorized
                response.setContentType("application/json;charset=UTF-8");  // 设置响应的字符编码为 UTF-8
                response.getWriter().write("{\"message\": \"token验证失败！\"}"); // 返回错误信息
                return; // 终止请求链
            }
        }
        filterChain.doFilter(request, response);
    }
}